<template>
  <div class="goods-item">
    <img :src="`${urlHost}${goods.product_img}`" alt="" />
    <div class="goods-title">{{ goods.product_name }}</div>
    <div class="goods-price">
      ￥ {{ goods.product_price }}
      <!-- 加购按钮 -->
      <van-button round type="danger" size="small" @click="insertCart"
        >加入购物车</van-button
      >
    </div>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { addCart } from '@/api/modules/cart'
import { useUserStore } from '@/store/user.store'
import { useRouter } from 'vue-router'
import { showSuccessToast, showFailToast } from 'vant'
const router = useRouter()
const urlHost = import.meta.env.VITE_APP_URL
const store = useUserStore()
const props = defineProps({
  goods: {
    type: Object, // 类型断言
    default: () => {
      return null
    }
  }
})

// 加入购物车
const insertCart = async () => {
  const { userInfo } = store.$state
  if (!userInfo) {
    // console.log('请先登录')
    showFailToast('请先登录！')
    router.push('/login')
  } else {
    const { product_id } = props.goods
    const { app_user_id: user_id } = userInfo

    try {
      const { data } = await addCart({ product_id, user_id })
      console.log(data)
      showSuccessToast('加入购物车成功')
    } catch (error) {
      // console.log(error)
      showFailToast('加入购物车失败')
    }
  }
}
</script>

<style lang="less" scoped>
.goods-item {
  background-color: #fff;
  width: 45%;
  border-radius: 15px;
  overflow: hidden;
  img {
    width: 100%;
  }
  .goods-title {
    // 超过两行溢出显示省略号
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .goods-price {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    font-size: 1.1rem;
  }
}
</style>
